<template>
  <div class="app-container">
    <el-dialog
      title="下级列表"
      width="1000px"
      :close-on-click-modal="false"
      :visible.sync="visible"
    >

      <!--    <el-form v-show="showSearch" ref="queryForm" :model="queryParams" :inline="true" label-width="68px">-->
      <!--      <el-form-item label="用户名称" prop="userName">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.userName"-->
      <!--          placeholder="请输入用户名称"-->
      <!--          clearable-->
      <!--          size="small"-->
      <!--          style="width: 240px"-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="手机号码" prop="phoneNumber">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.phoneNumber"-->
      <!--          placeholder="请输入手机号码"-->
      <!--          clearable-->
      <!--          size="small"-->
      <!--          style="width: 240px"-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="账号状态" prop="status">-->
      <!--        <el-select-->
      <!--          v-model="queryParams.status"-->
      <!--          placeholder="账号状态"-->
      <!--          clearable-->
      <!--          size="small"-->
      <!--          style="width: 240px"-->
      <!--        >-->
      <!--          <el-option-->
      <!--            v-for="dict in statusOptions"-->
      <!--            :key="dict.dictValue"-->
      <!--            :label="dict.dictLabel"-->
      <!--            :value="dict.dictValue"-->
      <!--          />-->
      <!--        </el-select>-->
      <!--      </el-form-item>-->

      <!--      &lt;!&ndash;      <el-form-item label="认证状态" prop="status">&ndash;&gt;-->
      <!--      &lt;!&ndash;        <el-select&ndash;&gt;-->
      <!--      &lt;!&ndash;          v-model="queryParams.authStatus"&ndash;&gt;-->
      <!--      &lt;!&ndash;          placeholder="认证状态"&ndash;&gt;-->
      <!--      &lt;!&ndash;          clearable&ndash;&gt;-->
      <!--      &lt;!&ndash;          size="small"&ndash;&gt;-->
      <!--      &lt;!&ndash;          style="width: 240px"&ndash;&gt;-->
      <!--      &lt;!&ndash;        >&ndash;&gt;-->
      <!--      &lt;!&ndash;          <el-option&ndash;&gt;-->
      <!--      &lt;!&ndash;            v-for="dict in authStatusOptions"&ndash;&gt;-->
      <!--      &lt;!&ndash;            :key="dict.dictValue"&ndash;&gt;-->
      <!--      &lt;!&ndash;            :label="dict.dictLabel"&ndash;&gt;-->
      <!--      &lt;!&ndash;            :value="dict.dictValue"&ndash;&gt;-->
      <!--      &lt;!&ndash;          />&ndash;&gt;-->
      <!--      &lt;!&ndash;        </el-select>&ndash;&gt;-->
      <!--      &lt;!&ndash;      </el-form-item>&ndash;&gt;-->

      <!--      <el-form-item>-->
      <!--        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>-->
      <!--        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>-->
      <!--      </el-form-item>-->
      <!--    </el-form>-->


      <el-table v-loading="loading" border :data="userList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" align="center"/>
        <el-table-column label="用户编号" align="center" prop="userId"/>
        <el-table-column
          width="150"
          label="用户头像"
          align="center"
          prop="avatar"
        >
          <template slot-scope="scope">
            <el-image
              :src="scope.row.avatar"
              style="width: 100px; height: 60px"
              :preview-src-list="[scope.row.avatar]"
            />
          </template>
        </el-table-column>

        <el-table-column
          width="150"
          label="用户昵称"
          align="center"
          prop="nickName"
          :show-overflow-tooltip="true"
        />

        <el-table-column
          width="150"
          label="用户姓名"
          align="center"
          prop="nickName"
          :show-overflow-tooltip="true"
        />

        <el-table-column
          label="手机号码"
          align="center"
          prop="phoneNumber"
          width="120"
        />
        <el-table-column
          label="用户类型"
          align="center"
          prop="userType"
          :formatter="userTypeFormat"
        />

        <!--      <el-table-column label="邀请码" align="center" prop="inviteCode" />-->

        <el-table-column label="身份证号" align="center" prop="cardNo"/>

        <el-table-column label="邀请码" align="center" prop="inviteCode"/>
        <el-table-column label="上级邀请码" align="center" prop="inviteFullCode"/>


        <el-table-column label="认证状态" align="center" :formatter="authFormat"/>


        <el-table-column label="直接上级姓名" align="center" prop="parentUser.realName"/>
        <el-table-column label="直接上级手机号" align="center" prop="parentUser.phoneNumber"/>
        <el-table-column label="直播收入(导入数据)" align="center" prop="livePrice"/>
        <el-table-column label="短视频收入(导入数据)" align="center" prop="videoPrice"/>
        <el-table-column label="直推人数" align="center" prop="directRecommend"></el-table-column>
        <el-table-column label="间推人数" align="center" prop="indirectRecommend"></el-table-column>


        <el-table-column label="直推佣金" align="center" prop="directRecommendPrice"/>
        <el-table-column label="直推直播佣金(我的直接下级开直播时给我贡献的钱)" align="center" prop="directRecommendZhiboPrice"/>
        <el-table-column label="直推短视频佣金(我的直接下级拍短视频时给我贡献的钱)" align="center" prop="directRecommendDuanshipinPrice"/>
        <el-table-column label="直推主播佣金(直接推广了主播)" align="center" prop="directRecommendZhuboPrice"/>
        <el-table-column label="直推团长佣金(直接推广了团长)" align="center" prop="directRecommendTuanzhangPrice"/>
        <el-table-column label="直推分公司佣金(直接推广了分公司)" align="center" prop="directRecommendFengongsiPrice"/>
        <el-table-column label="间推佣金" align="center" prop="indirectRecommendPrice"/>
        <el-table-column label="间推直播佣金(我的间接下级开直播时给我贡献的钱)" align="center" prop="indirectRecommendZhiboPrice"/>
        <el-table-column label="间推短视频佣金(我的间接下级拍短视频时给我贡献的钱)" align="center" prop="indirectRecommendDuanshipinPrice"/>
        <el-table-column label="间推主播佣金(间接推广了主播)" align="center" prop="indirectRecommendZhuboPrice"/>
        <el-table-column label="间推团长佣金(间接推广了团长)" align="center" prop="indirectRecommendTuanzhangPrice"/>
        <el-table-column label="间推分公司佣金(间接推广了分公司)" align="center" prop="indirectRecommendFengongsiPrice"/>
        <el-table-column label="平台赠送" align="center" prop="platformGift"/>
        <el-table-column label="股权分红" align="center" prop="equityGift"/>
        <el-table-column label="直推佣金+佣金+平台赠送+股权分红" align="center" prop="directAndIndirectRecommendPrice"/>
        <el-table-column label="提现金额" align="center" prop="withdrawalPrice"/>
        <el-table-column label="直推佣金+间推佣金+平台赠送+股权分红-提现金额(小程序上显示的)" align="center" prop="directAndIndirectRecommendTixianPrice"/>
        <el-table-column label="注册时间" align="center" prop="createTime" width="160">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          width="180"
          class-name="small-padding fixed-width"
        >
          <template v-if="scope.row.userId !== 1" slot-scope="scope">

            <el-button
              size="mini"
              type="text"
              icon="el-icon-news"
              @click="handleUpdate(scope.row)"
            >查看
            </el-button>

          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />


      <!-- 添加或修改参数配置对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-row>

            <el-col :span="12">
              <el-form-item label="用户昵称" prop="nickName">
                <el-input v-model="form.nickName" placeholder="请输入用户昵称" maxlength="30"/>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="用户姓名" prop="realName">
                <el-input v-model="form.realName" placeholder="请输入用户姓名" maxlength="30"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="手机号码" prop="phoneNumber">
                <el-input v-model="form.phoneNumber" placeholder="请输入手机号码" maxlength="11" disabled/>
              </el-form-item>
            </el-col>
            <!-- <el-col :span="12">
              <el-form-item label="归属部门" prop="deptId">
                <treeselect v-model="form.deptId" :options="deptOptions" :show-count="true" placeholder="请选择归属部门" />
              </el-form-item>
            </el-col> -->
          </el-row>
          <el-row>

            <el-col :span="12">
              <el-form-item label="用户性别">
                <el-select v-model="form.sex" placeholder="请选择">
                  <el-option
                    v-for="dict in sexOptions"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="dict.dictValue"
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="状态">
                <el-radio-group v-model="form.status">
                  <el-radio
                    v-for="dict in statusOptions"
                    :key="dict.dictValue"
                    :label="dict.dictValue"
                  >{{ dict.dictLabel }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>

          </el-row>

          <el-row>


          </el-row>

          <el-row>

            <el-col :span="24">
              <el-form-item label="头像">


                <el-image
                  :src="form.avatar"
                  style="width: 100px; height: 60px"
                  :preview-src-list="[form.avatar]"
                />

              </el-form-item>
            </el-col>

          </el-row>

          <el-table v-loading="loading" :data="form.detailList">
            <el-table-column label="抖音昵称" align="center" prop="tikName"/>
            <el-table-column label="抖音uid" align="center" prop="tikUid"/>
            <el-table-column label="抖音粉丝数" align="center" prop="tikFans"/>
          </el-table>


        </el-form>

      </el-dialog>

    </el-dialog>
  </div>
</template>

<script>
import {
  addUser,
  changeUserStatus, childList,
  delUser,
  exportUser,
  getUser,
  importTemplate,
  listUser,
  resetUserPwd,
  updateUser
} from '@/api/workbench/yshrjg';
import {getToken} from '@/utils/auth';
import {treeselect} from '@/api/system/dept';
import Treeselect from '@riophae/vue-treeselect';
import '@riophae/vue-treeselect/dist/vue-treeselect.css';
import editor from "quill/core/editor";

export default {
  name: 'User',
  computed: {
    editor() {
      return editor
    }
  },
  components: {Treeselect},
  data() {
    return {
      visible: false,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 弹出层标题
      title: '',
      // 部门树选项
      deptOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 部门名称
      deptName: undefined,
      // 默认密码
      initPassword: undefined,
      // 日期范围
      dateRange: [],
      // 状态数据字典
      statusOptions: [],
      userTypeOptions: [],
      // 资格认证状态
      authStatusOptions: [],
      // 性别状态字典
      sexOptions: [],
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      // 表单参数
      form: {},
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {Authorization: 'Bearer ' + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/system/user/importData'
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phoneNumber: undefined,
        status: undefined,
        deptId: undefined,
        userType: '01',
        userId: undefined,
        recommendType:undefined
      },
      // 列信息
      columns: [
        {key: 0, label: `用户编号`, visible: true},
        {key: 1, label: `用户名称`, visible: true},
        {key: 2, label: `用户姓名`, visible: true},
        {key: 3, label: `部门`, visible: true},
        {key: 4, label: `手机号码`, visible: true},
        {key: 5, label: `状态`, visible: true},
        {key: 6, label: `创建时间`, visible: true}
      ],
      // 表单校验
      rules: {}
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.getDicts('sys_normal_disable').then(response => {
      this.statusOptions = response.data;
    });
    this.getDicts('sys_user_sex').then(response => {
      this.sexOptions = response.data;
    });
    this.getConfigKey('sys.user.initPassword').then(response => {
      this.initPassword = response.msg;
    });
    this.getDicts('sys_user_type').then(response => {
      this.userTypeOptions = response.data;
    });
    this.getDicts('zb_apply_status').then(response => {
      this.authStatusOptions = response.data;
    });
  },
  methods: {
    /** 查询用户列表 */
    getRefList(userId, recommendType) {
      this.queryParams.userId = userId;
      this.visible = true;
      this.queryParams.recommendType = recommendType;
      childList(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.userList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        userId: undefined,
        deptId: undefined,
        userName: undefined,
        nickName: undefined,
        password: undefined,
        phoneNumber: undefined,
        email: undefined,
        sex: undefined,
        status: '0',
        remark: undefined,
        postIds: [],
        roleIds: []
      };
      this.resetForm('form');
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm('queryForm');
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case 'handleResetPwd':
          this.handleResetPwd(row);
          break;
        case 'handleAuthRole':
          this.handleAuthRole(row);
          break;
        default:
          break;
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      // this.getTreeselect();
      getUser().then(response => {
        this.postOptions = response.data.posts;
        this.roleOptions = response.data.roles;
        this.open = true;
        this.title = '添加用户';
        this.form.password = this.initPassword;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      // this.getTreeselect();
      const userId = row.userId || this.ids;
      getUser(userId).then(response => {
        this.form = response.data.user;
        this.postOptions = response.data.posts;
        this.roleOptions = response.data.roles;
        this.form.postIds = response.data.postIds;
        this.form.roleIds = response.data.roleIds;
        this.open = true;
        this.title = '查看用户';
        this.form.password = '';
      });
    },
    /** 重置密码按钮操作 */
    handleResetPwd(row) {
      this.$prompt('请输入"' + row.userName + '"的新密码', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        closeOnClickModal: false,
        inputPattern: /^.{5,20}$/,
        inputErrorMessage: '用户密码长度必须介于 5 和 20 之间'
      }).then(({value}) => {
        resetUserPwd(row.userId, value).then(response => {
          this.msgSuccess('修改成功，新密码是：' + value);
        });
      }).catch(() => {
      });
    },
    /** 分配角色操作 */
    handleAuthRole: function (row) {
      const userId = row.userId;
      this.$router.push('/auth/role/' + userId);
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.userId != undefined) {
            updateUser(this.form).then(response => {
              this.msgSuccess('修改成功');
              this.open = false;
              this.getList();
            });
          } else {
            addUser(this.form).then(response => {
              this.msgSuccess('新增成功');
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.userId || this.ids;
      this.$confirm('是否确认删除用户编号为"' + userIds + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function () {
        return delUser(userIds);
      }).then(() => {
        this.getList();
        this.msgSuccess('删除成功');
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有用户数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.exportLoading = true;
        return exportUser(queryParams);
      }).then(response => {
        this.download(response.msg);
        this.exportLoading = false;
      }).catch(() => {
      });
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = '用户导入';
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      importTemplate().then(response => {
        this.download(response.msg);
      });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, '导入结果', {dangerouslyUseHTMLString: true});
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    userTypeFormat(row) {
      return this.selectDictLabel(this.userTypeOptions, row.userType);
    },
    // 认证状态
    authFormat(row) {
      if (row.authStatus == '1') {
        return "已认证";
      } else if (row.authStatus == '2') {
        return "认证不通过";
      } else if (row.authStatus == '3') {
        return "认证中";
      } else {
        return "不再审核";
      }
    }
  }
};
</script>
